package com.study.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.study.common.ErrorCode;
import com.study.exception.BusinessException;
import com.study.mapper.UserMapper;
import com.study.pojo.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.study.contant.UserConstant.USER_LOGIN_STATE;

/**
* @author fruity
* @description 用户注册实现
* @createDate 2025-03-18 14:54:23
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Resource
    private UserMapper userMapper;
    /**
     * 盐值，混淆密码
     */
    private static final String SALT ="fruity";

    /**
     * 错误日志
     */
    private static Logger log= LoggerFactory.getLogger(UserServiceImpl.class);

    /**
     * 用户注册实现
     * @param userAccount 用户账户
     * @param userPassword 用户密码
     * @param checkPassword 第二次输入密码
     * @return 用户注册id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,String planetCode) {
        //1、校验
            //非空
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,planetCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }  //账号不小于4
        if(userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号小于4位");
        }  //密码和校验码不小于8
        if(userPassword.length()<8||checkPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码小于8位");
        }
        if(planetCode.length()>5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"内部编号大于5位");
        }
        //账号不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        //查找userAccount是否有特殊字符
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        //包含特殊字符返回-1
        if(matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号名包含特殊符号");
        }
        //校验两次密码相同
        if(!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不相同");
        }
        //账号不能重复
            //数据库查询条件(写在最后可以过滤一些因为前面条件不成立导致注册失败，就不用浪费去查询数据库的性能)
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            //判断userAccount是否等于传进来的userAccount
        queryWrapper.eq("userAccount",userAccount);
        long count = this.count(queryWrapper);
        if(count>0){
            //有人注册了
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号已被注册");
        }

        queryWrapper = new QueryWrapper<>();
        //判断userAccount是否等于传进来的userAccount
        queryWrapper.eq("planetCode",userAccount);
        count = this.count(queryWrapper);
        if(count>0){
            //内部用户编号重复
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"内部编号重复");
        }

        //2、密码加密
        //spring中自带的方法可以对密码进行加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //3、向数据库中插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveRes = this.save(user);
        //判断是否存入成功
        if(!saveRes){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户插入数据库失败");
        }
        //返回存入用户的id
        return user.getId();
    }

    /**
     * 用户登陆实现
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request  前端传来登录请求
     * @return 用户
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1、校验用户的帐号和密码是否合法
        //非空
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }  //账号不小于4
        if(userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号长度小于4位");
        }  //密码不小于8
        if(userPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码长度小于8位");
        }
        //账号不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号名包含特殊符号");
        }
        //2、密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",encryptPassword);
        //将满足条件的用户在数据库中查出来
        User user = userMapper.selectOne(queryWrapper);
        //用户不存在
        if(user==null){
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.NOT_LOGIN,"用户未注册");
        }

        //3、用户脱敏
        User safetyUser = getSafetyUser(user);


        //4、记录用户的登录态cookie
        request.getSession().setAttribute(USER_LOGIN_STATE,safetyUser);

        //返回脱敏后的用户
        return safetyUser;
    }

    /**
     * 用户脱敏
     * @param originalUser 未脱敏用户
     * @return 脱敏后的用户
     */
    @Override
    /*public User getSafetyUser(User originalUser){
        User safetyUser = new User();
        safetyUser.setId(originalUser.getId());
        safetyUser.setUsername(originalUser.getUsername());
        safetyUser.setUserAccount(originalUser.getUserAccount());
        safetyUser.setAvatarUrl(originalUser.getAvatarUrl());
        safetyUser.setGender(originalUser.getGender());
        safetyUser.setPhone(originalUser.getPhone());
        safetyUser.setEmail(originalUser.getEmail());
        safetyUser.setUserStatus(originalUser.getUserStatus());
        safetyUser.setCreateTime(originalUser.getCreateTime());
        safetyUser.setUserRole(originalUser.getUserRole());
        return safetyUser;
    }*/
    public User getSafetyUser(User originalUser) {
        User safetyUser = new User();
        BeanUtils.copyProperties(originalUser, safetyUser, "userPassword"); // 排除敏感字段
        return safetyUser;
    }

    /**
     * 用户注销
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        //移除用户登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }
}




